package com.joolun.web.controller.paynow;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.joolun.common.annotation.Anonymous;
import com.joolun.common.core.domain.AjaxResult;
import com.joolun.system.domain.PayLink;
import com.joolun.system.domain.PayOrder;
import com.joolun.system.domain.PayParam;
import com.joolun.system.service.IPayOrderService;
import com.joolun.web.ipaynow.utils.FormDateReportConvertor;
import com.joolun.web.ipaynow.utils.MD5Facade;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 支付回调后台Controller
 *
 * @author return
 * @date 2025-07-07
 */
@RestController
@RequestMapping("/ipaynow")
public class CallbackController {
    @Autowired
    private IPayOrderService iPayOrderService;
    /**
     *
     * 接收支付回调
     * @param
     * @return
     */
    @PostMapping("/back")
    @Anonymous
    public void payParam(HttpServletRequest req, HttpServletResponse resp){
        System.out.println("--------------------接收支付回调----------------------------");
        try {
            Map<String, String> dataMap = new HashMap<>();
            // 获取所有参数名
            java.util.Enumeration<String> paramNames = req.getParameterNames();
            // 遍历参数名，获取对应值
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                // 获取参数值（注意：可能存在多个值，这里取第一个）
                String paramValue = req.getParameter(paramName);
                System.out.println(paramName+"-------------" + paramValue);
                dataMap.put(paramName, paramValue);
            }
            //去除签名值
            String signature = dataMap.remove("signature");
            System.out.println("-----------获取回调参数dataMap：" + dataMap);
            //拿到自己应用的md5Key
            String md5Key = "gh4HwH7UarOCXRtP96lPD9KQd8xiEpT9";
            //验证签名
            boolean isValidSignature = MD5Facade.validateFormDataParamMD5(dataMap,md5Key,signature);
            System.out.println("-----------------------验签结果：" + isValidSignature);
            // 验签通过，补全订单信息
            if(isValidSignature) {
                // 根据订单号查询订单信息
                PayOrder payOrder = iPayOrderService.getOne(Wrappers.lambdaQuery(PayOrder.class).eq(PayOrder::getOrderNo,dataMap.get("mhtOrderNo")));
                // 支付成功时间
                payOrder.setPaymentTime(dataMap.get("payTime"));
                // 现在支付流水号
                payOrder.setNowPayOrderNo(dataMap.get("nowPayOrderNo"));
                // 用户所选渠道类型
                payOrder.setPayChannelType(dataMap.get("payChannelType"));
                // 交易状态：A001-订单支付成功，A002-订单支付失败，A006-交易关闭，A00I-订单未处理
                if("A001".equals(dataMap.get("transStatus"))){
                    payOrder.setIsPay("1");
                    payOrder.setStatus("1");
                }else if("A002".equals(dataMap.get("transStatus"))){
                    payOrder.setStatus("2");
                }else if("A006".equals(dataMap.get("transStatus"))){
                    payOrder.setStatus("3");
                }else if("A00I".equals(dataMap.get("transStatus"))){
                    payOrder.setStatus("0");
                }
                int payResult = iPayOrderService.updatePayOrder(payOrder);
                if(payResult > 0){
                    System.out.println("订单回调更新成功！");
                }else{
                    System.out.println("订单回调更新失败！---------请检查订单号------" + payOrder.getOrderNo() + "-----------订单情况");
                }
                resp.getOutputStream().write("success=Y".getBytes());
            }
            else{
                resp.getOutputStream().write("success=N".getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
